import * as THREE from "three";
import { model } from "./scene/mesh.js";
// import {tag} from "./scene/tag.js";
import { camera } from "./RendererCamera.js";
let intersects =  null
const choose = function(event, label) {
    const width = window.innerWidth;
    const height = window.innerHeight;
    // .offsetY、.offsetX以canvas画布左上角为坐标原点,单位px
    const px = event.offsetX;
    const py = event.offsetY;
    //屏幕坐标px、py转WebGL标准设备坐标x、y
    //width、height表示canvas画布宽高度
    const x = (px / width) * 2 - 1;
    const y = -(py / height) * 2 + 1;
    //创建一个射线投射器`Raycaster`
    const raycaster = new THREE.Raycaster();
    raycaster.setFromCamera(new THREE.Vector2(x, y), camera);
    const group = model.getObjectByName("粮仓");
    const meshArr = [];
    group.traverse((object) => {
      if (object.type === "Mesh") {
        meshArr.push(object);
      }
    });
    intersects = raycaster.intersectObjects(meshArr);
    if (intersects.length > 0) {
        const pos = new THREE.Vector3()
        intersects[0].object.getWorldPosition(pos)
        label.position.copy(pos)
        if(intersects[0].object.parent.name === "立筒仓"){
            label.position.y+= 36
        }else if(intersects[0].object.parent.name === "浅圆仓"){
            label.position.y+= 20
        }else if(intersects[0].object.parent.name === "平房仓"){
            label.position.y+=  17
        }
        label.scale.set(0.2,0.2,0.2)
        label.rotation.y = Math.PI/2
        model.add(label)
    }else{
        intersects = []
        if(label){
            model.remove(label)
        }
    }
}
export {choose,intersects}